package com.cn.xt.controller;
import com.cn.xt.constants.Constants;
import com.cn.xt.entity.*;
import com.cn.xt.enums.XtServerEnum;
import com.cn.xt.service.ISysMenuService;
import com.cn.xt.service.ISysRoleService;
import com.cn.xt.service.ISysSerialNumberService;
import com.cn.xt.service.impl.SysMenuServiceImpl;
import com.cn.xt.utils.CollectionUtil;
import com.cn.xt.vo.bean.ResourcesBean;
import com.cn.xt.vo.rsp.ResponseBase;
import com.cn.xt.vo.rsp.fegin.ResponseRsp;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import jakarta.validation.Valid;
import org.apache.commons.lang3.StringUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import javax.annotation.Resource;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 *  控制器
 * @author sunyongzheng
 * @since 2021-03-15
 */
@Api(value = "角色管理")
@RestController
@RequestMapping("sysRole")
public class SysRoleController extends BaseController {

    @Resource
    private ISysRoleService sysRoleService;

    @Resource
    private ISysMenuService sysMenuService;

    @Resource
    private SysMenuServiceImpl sysMenuServiceImpl;

    @Resource
    private ISysSerialNumberService sysSerialNumberService;

    private static String MODULE_NAME = "角色管理";
    private static String MODULE_CODE = "Role";
    private static String MODULE_FRONT = "Role_";

    @ApiOperation(value = "分页查询角色", notes = "分页查询角色")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "currentPage", value = "当前第几页", required = true),
        @ApiImplicitParam(name = "pageSize", value = "每页显示几条", required = true),
        @ApiImplicitParam(name = "roleName", value = "角色名称", required = false)
    })
    @RequestMapping(value = "/selectRolePage", method = RequestMethod.POST)
    public ResponseBase selectPage(@RequestParam("currentPage") Integer currentPage,@RequestParam("pageSize") Integer pageSize,@RequestParam(value = "roleName" ,required = false ) String roleName) {
        try {
            //添加自定义查询参数
            QueryWrapper<SysRole> wrapper = new QueryWrapper();
            wrapper.eq("is_delete",0);
            wrapper.orderByDesc("create_time");
            if(StringUtils.isNotBlank(roleName)){
                wrapper.like("role_name","%"+roleName+"%");
            }
            Page<SysRole> page = new Page<>(currentPage,pageSize);
            IPage<SysRole> result = sysRoleService.getBaseMapper().selectPage(page,wrapper);
            return  setResultSuccess(result);
        } catch (Exception e) {
            e.printStackTrace();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            e.printStackTrace(new PrintStream(baos));
            //系统错误
            return setResult(Constants.HTTP_RES_CODE_500, localeMessage.getMessage("sys.common.error"), null);
        }
    }

    @ApiOperation(value = "添加角色", notes = "添加角色")
    @Transactional
    @RequestMapping(value = "/addRole", method = RequestMethod.POST)
    public ResponseBase add(@Valid @RequestBody SysRoleAdd sysRoleAdd, BindingResult bindingResult) {
        try {
            // 验证实体输入参数
            ResponseBase validResult = validateField(bindingResult);
            if (validResult != null) {
                return validResult;
            }
            //查重
            SysRole role = this.duplicateCheck(sysRoleAdd);
            if(role != null){
                return setResult(Constants.HTTP_RES_CODE_401, localeMessage.getMessage("sys.common.role.name.isExist"), null);
            }
            //获取流水号
            SysSerialNumber sysSerialNumber =  new SysSerialNumber();
            sysSerialNumber.setModuleName(MODULE_NAME);
            sysSerialNumber.setModuleCode(MODULE_CODE);
            sysSerialNumber.setPreposeStr(MODULE_FRONT);
            String serialNumber = sysSerialNumberService.gainSerialNumber(sysSerialNumber);
            //插入角色信息
            SysRole sysRole = new SysRole();
            sysRole.setRoleCode(serialNumber);
            sysRole.setRoleDesc(sysRoleAdd.getRoleDesc());
            sysRole.setRoleName(sysRoleAdd.getRoleName());
            boolean falg = sysRoleService.save(sysRole);
            if(falg){
                this.addRoleMenu(sysRoleAdd.getMenuList(),sysRole.getId());
            }
        } catch (Exception e) {
            e.printStackTrace();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            e.printStackTrace(new PrintStream(baos));
            //系统错误
            return setResult(Constants.HTTP_RES_CODE_500, localeMessage.getMessage("sys.common.error"), null);
        }
        return setResultSuccess();
    }

    /**
     * @description
     * @author sunyongzheng
     * @date 2021/3/17 14:08
     */
    public SysRole duplicateCheck(SysRoleAdd sysRoleAdd){
        //角色名查重
        QueryWrapper<SysRole> wrapper = new QueryWrapper();
        wrapper.eq("role_name",sysRoleAdd.getRoleName());
        SysRole role = sysRoleService.getOne(wrapper);
        return role;
    }

    @ApiOperation(value = "修改角色", notes = "修改角色")
    @Transactional
    @RequestMapping(value = "/updateRole", method = RequestMethod.POST)
    public ResponseBase update(@Valid @RequestBody SysRoleAdd sysRoleAdd, BindingResult bindingResult) {
        try {
            // 验证实体输入参数
            ResponseBase validResult = validateField(bindingResult);
            if (validResult != null) {
                return validResult;
            }
            //查重
            SysRole role = this.duplicateCheck(sysRoleAdd);
            if(role != null && !role.getId().equals(sysRoleAdd.getId())){
                return setResult(Constants.HTTP_RES_CODE_401, localeMessage.getMessage("sys.common.role.name.isExist"), null);
            }
            //插入角色信息
            SysRole sysRole = new SysRole();
            sysRole.setRoleCode(sysRoleAdd.getRoleCode());
            sysRole.setRoleDesc(sysRoleAdd.getRoleDesc());
            sysRole.setRoleName(sysRoleAdd.getRoleName());
            sysRole.setId(sysRoleAdd.getId());
            sysRoleService.updateById(sysRole);
            sysRoleService.deleteRoleMenuById(sysRoleAdd.getId());
            this.addRoleMenu(sysRoleAdd.getMenuList(),sysRoleAdd.getId());
        } catch (Exception e) {
            e.printStackTrace();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            e.printStackTrace(new PrintStream(baos));
            //系统错误
            return setResult(Constants.HTTP_RES_CODE_500, localeMessage.getMessage("sys.common.error"), null);
        }
        return setResultSuccess();
    }

   /**
    * @description 插入角色权限关系
    * @author sunyongzheng
    * @date 2021/3/15 14:52
    */
    public boolean addRoleMenu(List<String> menuList,String roleId){
        try {
            if (!menuList.isEmpty()) {
                for (int i = 0; i < menuList.size(); i++) {
                    SysRoleMenu sysRoleMenu = new SysRoleMenu();
                    sysRoleMenu.setId(UUID.randomUUID().toString());
                    sysRoleMenu.setRoleId(roleId);
                    sysRoleMenu.setMenuId(menuList.get(i));
                    sysRoleService.saveRoleMenu(sysRoleMenu);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            e.printStackTrace(new PrintStream(baos));
            return false;
        }
        return true;
    }

    @ApiOperation(value = "删除角色", notes = "删除角色")
    @RequestMapping(value = "/delRole", method = RequestMethod.GET)
    public ResponseBase del(@RequestParam String id) {
        try {
            boolean delFlag = sysRoleService.deleteRoleById(id);
            if(delFlag){
                sysRoleService.deleteRoleMenuById(id);
            }
        } catch (Exception e) {
            e.printStackTrace();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            e.printStackTrace(new PrintStream(baos));
            //系统错误
            return setResult(Constants.HTTP_RES_CODE_500, localeMessage.getMessage("sys.common.error"), null);
        }
        return setResultSuccess();
    }

    /**
     * @description 新增时获取全部菜单信息
     * @author sunyongzheng
     * @date 2021/3/15 11:42
     */
    @ApiOperation(value = "获取菜单列表", notes = "获取菜单列表")
    @RequestMapping(value = "/getMenuList", method = RequestMethod.GET)
    public ResponseBase getMenuList(@RequestParam(value = "sysCode",required = true) String sysCode,@RequestParam(value = "roleId" ,required = false) String roleId) {
        ResponseRsp responseRspAll = new ResponseRsp();
        try {
            responseRspAll = getAllMenuTree(sysCode);
            if(roleId != null && roleId != ""){
                List<SysMenu> menuList = getMenuByRole(roleId);
                responseRspAll.setAllList(menuList);
            }
        } catch (Exception e) {
            e.printStackTrace();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            e.printStackTrace(new PrintStream(baos));
            //系统错误
            return setResult(Constants.HTTP_RES_CODE_500, localeMessage.getMessage("sys.common.error"), null);
        }
        return setResultSuccess(responseRspAll);
    }
    /**
     * @description
     * @author sunyongzheng
     * @date 2021/3/17 14:11
     */
    public ResponseRsp getAllMenuTree(String sysCode) {
        if(StringUtils.isEmpty(sysCode)){
            sysCode = XtServerEnum.SIX.getServerId();
        }
        //查询
        ResponseRsp result = sysMenuService.getAllMenu(sysCode);
        result.setAllList(null);
        return  result;
    }
    /**
     * @description
     * @author sunyongzheng
     * @date 2021/3/17 14:11
     */
    public List<SysMenu> getMenuByRole(String role) {
        List<SysMenu> menuList = null;
        try{
            menuList = sysRoleService.getMenuByRole(role);
        }catch (Exception e){
            e.printStackTrace();
        }
        return menuList;
    }
    @ApiOperation(value = "根据用户id获取角色集合", notes = "获取菜单列表")
    @RequestMapping(value = "/getRoleByUserId", method = RequestMethod.GET)
    public ResponseBase getRoleByUserId(@RequestParam(value = "userId",required = true) String userId){
        try {
            return setResultSuccess(sysRoleService.getRoleByUserId(userId));
        } catch (Exception e) {
            e.printStackTrace();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            e.printStackTrace(new PrintStream(baos));
            //系统错误
            return setResult(Constants.HTTP_RES_CODE_500, localeMessage.getMessage("sys.common.error"), null);
        }
    }
}
